package com.web.kdl.config.security.components;

import cn.hutool.json.JSONUtil;
import com.web.kdl.common.result.CommonResult;
import com.web.kdl.common.result.ReturnCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author： shulibin
 * @Date： 2025/7/25 10:43
 * @Describe：拒绝访问处理类
 */
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    // 没有权限访问时的处理方法
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        // 响应 403 没有相关权限
        response.getWriter().println(JSONUtil.parse(CommonResult.error(ReturnCode.FORBIDDEN.getCode())));
        response.getWriter().flush();
    }
}
